<template>
  <div class="user_details">
    <!-- 头像 -->
    <div class="userface">
      <div class="photo">
        <div class="box">
          <img :src="personData.userFace" style="width: 100px;width: 100px;">
        </div>
      </div>
      <div style="padding-top:50px;text-align:right">
        <el-button size="small" type="text" @click="updateIcon">修改头像</el-button>
      </div>
    </div>
    <div class="info">
      <el-form label-width="100" size="small">
        <el-form-item label="登录用户">{{ currentUser.username }}</el-form-item>
        <el-form-item label="用户姓名">{{ currentUser.realname }}</el-form-item>
        <el-form-item label="用户手机">{{ currentUser.telephone }}</el-form-item>
        <el-form-item label="用户性别">
          <div v-if="currentUser.gender">
            <!-- female女male男 -->
            <!-- {{ currentUser.gender==='male'?'男':'女' }} -->
            <span v-if="currentUser.gender === 'male'">男</span>
            <span v-else-if="currentUser.gender === 'female'">男</span>
            <span v-else>--</span>
            <i v-if="currentUser.gender === 'male'" class="el-icon-male green_info" />
            <i v-else-if="currentUser.gender === 'female'" class="el-icon-female red_info" />
          </div>
          <div v-else>暂无</div>
        </el-form-item>
        <el-form-item label="用户角色">{{ currentUser.role === 0 ? '管理员' : '普通用户' }}</el-form-item>
        <el-form-item label="用户生日">{{ currentUser.dob ? currentUser.dob.split(' ')[0] : '暂无' }}</el-form-item>
        <el-form-item label="注册时间">{{ currentUser.registerTime || '暂无' }}</el-form-item>
        <el-form-item label="邮箱">{{ currentUser.email || '暂无' }}</el-form-item>
        <el-form-item label="用户状态">
          <el-tag size="small" :type="currentUser.status == '正常' ? 'success' : 'danger'">{{ currentUser.status }}</el-tag>
        </el-form-item>
      </el-form>
    </div>
    <div style="text-align:right;padding-right:200px;border-top:1px solid #f4f4f4">
      <el-button size="small" type="text" @click="updateInfo">修改个人信息</el-button>
    </div>
    <!-- 个人信息模态框 -->
    <el-dialog
      title="提示"
      :visible.sync="visible"
      width="50%"
      class="customer_modal"
      @close="clearValidate('personal_form')"
    >
      <el-form ref="personal_form" size="small" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="登录用户" prop="username">
          <el-input disabled :placeholder="form.username" />
        </el-form-item>
        <!-- <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password"></el-input>
        </el-form-item>-->
        <el-form-item label="姓名" prop="realname">
          <el-input v-model="form.realname" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户手机" prop="telephone">
          <el-input v-model="form.telephone" />
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="出生日期" prop="dob">
          <el-date-picker v-model="form.dob" value-format="yyyy-MM-dd" type="date" placeholder="选择出生日期" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="visible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="submitForm">确 定 修 改</el-button>
      </span>
    </el-dialog>
    <!-- /个人信息模态框 -->
    <!-- 修改头像模态框 -->
    <el-dialog width="30%" title="更改头像" :visible.sync="Visible">
      <!-- model属性绑定的变量是表单对象 表单校验需要声明校验规则 使用prop对必填项进行校验 -->
      <!-- ref引用 类似于id -->
      <el-form ref="myForm" :model="form" :rules="rules">
        <el-row>
          <el-col>
            <el-form-item label="头像上传" :label-width="formLabelWidth" prop="imageUrl">
              <el-upload
                class="avatar-uploader"
                action="http://121.4.83.32:7006/UploadControlle/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="Visible = false">取 消</el-button>
        <el-button type="primary" @click="toSave">确 定</el-button>
      </div>
    </el-dialog>
    <!-- /更改头像模态框 -->
  </div>
</template>
<script>
import { saveOrUpdate, alterUserface } from '@/api/user'
import { mapGetters, mapActions, mapState } from 'vuex'
import { uploadFileURL, showFileURL } from '@/utils/config'
import { post, get } from '@/utils/request'
export default {
  name: 'Personal',
  props: ['userid'],
  data() {
    return {
      personData: {},
      userFaceData: {},
      // 表单域标签宽度
      formLabelWidth: '120px',
      uploadFileURL,
      imageUrl: '',
      // 展示的用户
      currentUser: {},
      form: {},
      formIcon: {},
      visible: false,
      Visible: false,
      rules: {
        realname: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        gender: [{ required: true, message: '请选择性别', trigger: 'change' }]
      },
      rulesIcon: {
        userFace: [
          { required: true, message: '请输入头像地址', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['user']),
    ...mapState('user', ['current_d'])
  },
  async created() {
    if (this.userid) {
      // 通过id获取数据
      await this.findUserById({ id: this.userid })
      this.currentUser = this.current_d
    } else {
      // 通过id获取数据
      await this.findUserById({ id: this.user.id })
      this.currentUser = this.current_d
      // this.currentUser = this.user;
    }
    this.getMessage()
  },
  methods: {
    // 获取个人信息
    async getMessage() {
      const res = await get('/baseUser/cascadeRoleFindAll')
      // console.log(res.data, '信息');
      // 将后端获取的数据赋值给表格数据源
      this.personData = res.data.filter(item => item.id == this.user.id)
      this.personData.userFace = res.data[0].userFace
    },
    // 点击确定进行保存
    toSave() {
      // 对表单进行校验
      this.$refs['myForm'].validate(async(valid) => {
        if (valid) {
          // 校验通过--->发起一个保存请求
          console.log(this.form)
          const res = await post('/baseUser/alterUserface', this.form)
          if (res.status == 200) {
            this.$message({
              type: 'success',
              message: res.message
            })
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
          this.personData.userFace = this.form.userface
          this.getMessage()
          // 模态框关闭
          this.Visible = false
          // 重新载入数据
          // this.getUserFace();
        } else {
          // 校验不通过--->return false
          return false
        }
      })
    },
    // 图片上传成功的回调函数
    handleAvatarSuccess(res, file) {
      this.form.imageUrl = URL.createObjectURL(file.raw)
      console.log(this.form.imageUrl, '122')
      // console.log(res,'11');
      // 上传图片成功后 将图片地址设置给表单对象url属性
      // this.form.userFace = res.data;
      this.imageUrl = res.data
      this.form.userface = this.imageUrl
      // console.log(this.form.userFace,'ssssss');
    },
    // 图片上传之前触发的函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    ...mapActions('user', ['getInfo', 'findUserById']),
    /**
     * @description: 图片上传成功
     * @param {*} res
     * @param {*} file
     * @return {*}
     */
    // uploadSuccess(res, file) {
    //   this.imageUrl = URL.createObjectURL(file.raw);
    //   this.formIcon.userface = showFileURL + res.data.id;
    // },
    /**
     * @description: 图片上传之前
     * @param {*} file
     * @return {*}
     */
    beforeUpload(file) {
      const isLt3M = file.size / 1024 / 1024 < 3
      if (!isLt3M) {
        this.$message.error('上传头像图片大小不能超过 3MB!')
      }
      return isLt3M
    },
    /**
     * @description: 更改个人信息按钮事件
     * @param {*}
     * @return {*}
     */
    updateInfo() {
      this.form = { ...this.currentUser }
      this.visible = true
    },
    /**
     * @description: 更改头像按钮事件
     * @param {*}
     * @return {*}
     */
    updateIcon() {
      this.Visible = true
      this.form.id = this.user.id
      this.form.imageUrl = this.personData.userFace
    },
    /**
     * @description: 提交头像
     * @param {*}
     * @return {*}
     */
    submitIconForm() {
      this.$refs['icon_form'].validate(async(valid) => {
        if (valid) {
          const res = await alterUserface(this.formIcon)
          this.visibleIcon = false
          this.$message({ message: res.message, type: 'success' })
          if (this.userid) {
            /* this.currentUser = {
              ...this.currentUser,
              userFace: this.formIcon.userface,
            }; */
            // 通过id获取数据
            await this.findUserById({ id: this.userid })
            this.currentUser = this.current_d
          } else {
            this.getInfo().then(() => {
              this.currentUser = this.user
            })
          }
        } else {
          return false
        }
      })
    },
    /**
     * @description: 提交用户信息
     * @param {*}
     * @return {*}
     */
    async submitForm() {
      this.Visible = false
      const res = await saveOrUpdate(this.form)
      this.$message({ message: res.message, type: 'success' })
    },
    // 重置表单校验
    clearValidate(form) {
      this.$refs[form].clearValidate()
    }
  }
}
</script>
<style lang="scss" scoped>
.userface {
  display: flex;
  padding: 1em 200px;

  &>div {
    flex: 1;
  }

  .photo {
    .box {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      overflow: hidden;
    }

    img {
      width: 100%;
      height: 100%;
    }
  }

  border-bottom: 2px solid #f4f4f4;
  margin-bottom: 1em;
}
</style>

